package com.sooncode.project.focusservice.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.sooncode.project.core.finder.Finder;
import com.sooncode.project.core.model.DomainException;
import com.sooncode.project.focusservice.model.ClassReport;
import com.sooncode.project.focusservice.model.Classes;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Map;

@Service
public class DownloadReportService {
    public void downloadReport(String classesId, HttpServletResponse response) {
        InputStream templateFile = getClass().getResourceAsStream("/classReport.xlsx");
        String fileName="";
        try {
            Classes classes=new Finder<>(Classes.class).byId(classesId);
            fileName = URLEncoder.encode(classes.getName()+"评测报告", "UTF-8");
        }catch (Exception ex){}
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
            //.registerWriteHandler(new MyExcelHandler())
            .withTemplate(templateFile).build()) {
            WriteSheet  listSheet = EasyExcel.writerSheet("评测列表").build();
            ClassReport classReport = new ClassReport();
            Map dataMap=classReport.getTestListData(classesId);
            excelWriter.fill(dataMap.get("items"),listSheet);
            excelWriter.fill(dataMap.get("data"),listSheet);
            WriteSheet  analysisSheet = EasyExcel.writerSheet("数据分析").build();
            excelWriter.fill(dataMap.get("analysisItems"),analysisSheet);
            excelWriter.fill(dataMap.get("data"),analysisSheet);
        }catch (Exception ex) {
            ex.printStackTrace();
            throw new DomainException("导出文件时发生错误");
        }
    }
}
